using AutoMapper;
using BaseData.Domain;
using BaseData.ErrorCode;
using BaseData.Infrastructrue.Interfaces;
using BaseData.ReadApi.Application.Command.Permissions;
using BaseData.ReadApi.Dto;
using MediatR;

namespace BaseData.ReadApi.Application.CommandHandler.Permissions
{
    /// <summary>
    /// 处理获取权限详情命令的处理器
    /// </summary>
    public class GetPermissionDetailCommandHandler : IRequestHandler<GetPermissionDetailCommand, Apiresult<PermissionDetailOutput>>
    {
        private readonly IBasepository<UserInfo> userpository;  // 用户信息仓储接口
        private readonly IBasepository<Role> rolepository;  // 角色仓储接口
        private readonly IBasepository<UserRole> uRpository;  // 用户角色仓储接口
        private readonly IBasepository<Permission> permisspository;  // 权限仓储接口
        private readonly IBasepository<RolePermiss> rolePerpository;  // 角色权限仓储接口
        private readonly IMapper mapper;  // 对象映射器
        private readonly ILogger<GetPermissionDetailCommandHandler> logger;  // 日志记录器

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="_userpository">用户信息仓储</param>
        /// <param name="_rolepository">角色仓储</param>
        /// <param name="_URpository">用户角色仓储</param>
        /// <param name="_permisspository">权限仓储</param>
        /// <param name="_rolePerpository">角色权限仓储</param>
        /// <param name="_mapper">对象映射器</param>
        /// <param name="_logger">日志记录器</param>
        public GetPermissionDetailCommandHandler(
            IBasepository<UserInfo> _userpository,
            IBasepository<Role> _rolepository,
            IBasepository<UserRole> _URpository,
            IBasepository<Permission> _permisspository,
            IBasepository<RolePermiss> _rolePerpository,
            IMapper _mapper,
            ILogger<GetPermissionDetailCommandHandler> _logger)
        {
            userpository = _userpository;
            rolepository = _rolepository;
            uRpository = _URpository;
            permisspository = _permisspository;
            rolePerpository = _rolePerpository;
            mapper = _mapper;
            logger = _logger;
        }

        /// <summary>
        /// 处理获取权限详情命令
        /// </summary>
        /// <param name="request">获取权限详情的请求数据</param>
        /// <param name="cancellationToken">取消标记</param>
        /// <returns>返回权限详情结果</returns>
        public async Task<Apiresult<PermissionDetailOutput>> Handle(GetPermissionDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 查找权限信息
                var permission = await permisspository.GetModel(p => p.PermissionId == request.PermissionId);
                if (permission == null)
                {
                    return new Apiresult<PermissionDetailOutput>
                    {
                        Code = ResultCode.查询失败,
                        Message = "权限不存在"
                    };
                }

                // 创建权限详情输出对象
                var result = mapper.Map<PermissionDetailOutput>(permission);

                // 统计拥有该权限的角色数量
                var roleCount = rolePerpository.GetAll().Count(rp => rp.PermissionId == request.PermissionId);
                result.RoleCount = roleCount;

                // 统计拥有该权限的用户数量（通过角色关联）
                var roleIds = rolePerpository.GetAll()
                    .Where(rp => rp.PermissionId == request.PermissionId)
                    .Select(rp => rp.RoleId)
                    .ToList();
                
                var userCount = 0;
                if (roleIds.Any())
                {
                    userCount = uRpository.GetAll().Count(ur => roleIds.Contains(ur.RoleId));
                }
                result.UserCount = userCount;

                return new Apiresult<PermissionDetailOutput>
                {
                    Code = ResultCode.查询成功,
                    Result = result
                };
            }
            catch (Exception ex)
            {
                // 记录日志
                logger.LogError($"GetPermissionDetailCommandHandler.Handle方法异常：{ex.Message},{ex.StackTrace}");
                return new Apiresult<PermissionDetailOutput>
                {
                    Code = ResultCode.查询失败,
                    Message = "系统异常，获取权限详情失败"
                };
            }
        }
    }
}